/* $Id: db_select.js,v 1.1.1.1 2014/08/23 06:57:06 ymlam Exp $ Copyright (C) 2014 Link2Tek LLC */

// Rememeber to also include the xml.js file in the source file with, e.g.
// <script language="javascript" type="text/javascript" src="../_js/xml.js"></script>

var xmlhttp = false;

try
{
  xmlhttp = new XMLHttpRequest();
} catch (e)
{
  xmlhttp = false;
}

/**
 * error shows up as alert screen
 * @param sid: of the form PHPSESSID=xxxxx
 * @param proc: processing function that takes DOM object as its only argument
 *   This DOM object is constructed from the returned XML from db_select.php
 */
function accessDbQuery(sql, sid, proc)
{
  var url="../_include/db_select.php?" + sid + "&query=" + encodeURIComponent(sql);
  //alert(url);
  xmlhttp.open("GET", url, true);
  
  xmlhttp.onreadystatechange = function()
  {
    if (xmlhttp.readyState == 4)
    {
      var responseXML = xmlhttp.responseText;
      //alert(responseXML);
      var xmlDoc = loadXMLString(responseXML);
      // Check for error, throwing exception
      if (xmlDoc == null)
      {
         alert('Error: bad xml');
         return;
      }
      var node = xmlDoc.selectSingleNode('/result/error');
      if (node != null)
      {
        alert("Error: " + node.text);
        return;
      }
      //alert("invoking proc()");
      proc(xmlDoc);
    }
  }
  xmlhttp.send("");
}

/**
 * @return value of xpath '/result/count' from xml returned from db_select.php
 * @param xmlDoc - DOM constructed from xml string returned from db_select.php
 */
// YML: Not used as of 8/12/2014
function dbQuery_getCount(xmlDoc)
{
  var node =  xmlDoc.selectSingleNode('/result/count');
  if (node == null) throw "xpath '/result/count' not found";
  var count = node.text;
  //alert("count: '" + count + "'");
  return count; 
}

// Performs like the php function with the same name to assist
// generation of quote-safe field values for sql
function addslashes(string)
{
  // TODO
  return string;
}

